package com.ljyhhh.SmartCity.service


import android.annotation.SuppressLint
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.util.Log
import androidx.core.app.NotificationCompat
import com.ljyhhh.SmartCity.R
import com.ljyhhh.SmartCity.activity.server.MyServer
import java.text.SimpleDateFormat
import java.util.*

class MyNotificationService: Service() {





    override fun onBind(intent: Intent): IBinder {
        Log.d("server ----","onBind")
        TODO("Return the communication channel to the service.")
    }


    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        val manager = this.getSystemService(Context.NOTIFICATION_SERVICE) as
                NotificationManager
        Log.d("server ----","onStartCommand")
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel("normal", "Normal", NotificationManager.IMPORTANCE_DEFAULT)
            manager.createNotificationChannel(channel)

        }
        val handler = Handler(Looper.getMainLooper())
        val runnable = object : Runnable {
            @SuppressLint("SimpleDateFormat")
            override fun run() {
                val sdf = SimpleDateFormat("dd/M/yyyy hh:mm:ss")
                val currentDate = sdf.format(Date())

                val intent=Intent(applicationContext,MyServer::class.java)
                val pi=PendingIntent.getActivity(applicationContext,0,intent,0)
                // 在这里创建并显示通知
                val notification = NotificationCompat.Builder(this@MyNotificationService, "normal")
                    .setChannelId("normal")
                    .setContentTitle("time")
                    .setContentText(currentDate)
                    .setSmallIcon(R.drawable.smail_icon)
                    .setContentIntent(pi)

                with(manager){
                    notify(1,notification.build())
                }
                handler.postDelayed(this, 1000*60)


            }
        }
        handler.post(runnable)

        return super.onStartCommand(intent, flags, startId)
    }


    override fun onDestroy() {
        Log.d("server","onDestroy")
        super.onDestroy()
    }
}